package com.xhtt.fzxy.console.handler;

import net.lastcoder.ifserver.util.TextUtils;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * auth: WenYF
 * date: 2018/5/5
 */
public abstract class BaseHandler {
    public static final Logger Log = LoggerFactory.getLogger(BaseHandler.class);

    protected static final HashMap<String, String> sHeaders = new HashMap<>();
    // TODO 如果又访问其他服务器
    protected static String sBaseUrl = "http://127.0.0.1:9628/";
    static {
        // TODO sHeaders
        
    }
    
    public static Map<String, String> formatQueryString(String query) {
        HashMap<String, String> maps = new HashMap<>();
        String[] splits = query.split("&");

        for (String one : splits) {
            String[] oneSplits = one.split("=");
            maps.put(oneSplits[0], oneSplits.length > 1 ? oneSplits[1] : "");
        }

        return maps;
    }
    
    public String getData(HttpServletRequest baseRequest) throws IOException {
        String encoding = baseRequest.getCharacterEncoding();
        if(encoding == null) {
            encoding = "UTF-8";
        }

        BufferedReader reader;
        final ServletInputStream in = baseRequest.getInputStream();
        reader = new BufferedReader(new InputStreamReader(in, encoding)) {
            public void close() throws IOException {
                in.close();
            }
        };

        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[8192];
        int size, count = 0;
        while ((size = reader.read(buffer)) != -1) {
            sb.append(buffer, 0, size);
            count += size;
            // Log.debug("size:" + size);
        }
        return sb.toString();
    }
    
    private static void doRespond(String method, HttpServletResponse response, String ret) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/json");
        byte[] content = ret.getBytes(net.lastcoder.ifserver.Constants.DEFAUT_CAHRSET);
        response.setContentLength(content.length);
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream os = response.getOutputStream();
        os.write(content);
        os.flush();

        Log.debug("prcess [" + method + "] request ret length : " + content.length);
    }

    /**对返回的数据是否包装,如：{retcode:xxx,retmsg:xxx,data:{你的将要包装的数据}}
     * @return true包装，false直接返回ret.data
     */
    protected boolean isWrapperRet() {
        return true;
    }
    
    public void baseProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ProcessRetWrapper ret = new ProcessRetWrapper();
        ret.errcode = 0;
        ret.data = false;
        process(req, resp, ret);
        if (ret.done) {
            return;
        }

        Object retObj;
        if (isWrapperRet()) {
            JSONObject retJson = new JSONObject();
            retObj = retJson;
            if (ret.errcode != 0) {
                retJson.put("errcode", ret.errcode);
                retJson.put("errmsg", TextUtils.isEmpty(ret.errmsg) ? "未知错误" : ret.errmsg);
            } else {
                retJson.put("errcode", ret.errcode);
                retJson.put("data", ret.data);
            }
        } else {
            retObj = ret.data;
        }

        doRespond(req.getRequestURL().toString(), resp, retObj.toString());
    }
    
    public abstract void process(HttpServletRequest req, HttpServletResponse resp, ProcessRetWrapper ret) throws IOException;

    public static class ProcessRetWrapper {
        public Object data;
        public int errcode = 0;
        public String errmsg;
        public boolean done;
    }
}
